<template>
  <div class="customer-detail">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>客户详情</span>
          <div class="header-actions">
          <el-button @click="goBack">返回</el-button>
          <el-button type="primary" @click="handleEdit">编辑</el-button>
          <el-button type="success" @click="handleFollowUp">新增跟进</el-button>
          <el-button type="warning" @click="handleTransfer">转移客户</el-button>
          <el-dropdown @command="handleStatusAction" trigger="click">
            <el-button type="info">
              状态变更
              <el-icon class="el-icon--right">
                <arrow-down />
              </el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="potential">标记为潜在客户</el-dropdown-item>
                <el-dropdown-item command="intention">标记为意向客户</el-dropdown-item>
                <el-dropdown-item command="deal">标记为成交客户</el-dropdown-item>
                <el-dropdown-item command="invalid" divided>标记为失效客户</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
        </div>
      </template>

      <!-- 基本信息 -->
      <el-descriptions title="基本信息" :column="3" border class="info-section">
        <el-descriptions-item label="客户姓名">{{ customer.customerName }}</el-descriptions-item>
        <el-descriptions-item label="手机号码">{{ customer.phone }}</el-descriptions-item>
        <el-descriptions-item label="客户状态">
          <el-tag :type="getStatusType(customer.customerStatus)">
            {{ getStatusLabel(customer.customerStatus) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="客户来源">
          {{ getSourceLabel(customer.customerSource) }}
        </el-descriptions-item>
        <el-descriptions-item label="所属渠道">{{ customer.channelName }}</el-descriptions-item>
        <el-descriptions-item label="负责人">{{ customer.ownerUserName }}</el-descriptions-item>
        <el-descriptions-item label="分配状态">
          <el-tag :type="customer.allocationStatus === 'allocated' ? 'success' : 'warning'">
            {{ customer.allocationStatus === 'allocated' ? '已分配' : '未分配' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="贷款金额">
          <span v-if="customer.loanAmount">{{ formatCurrency(customer.loanAmount) }}</span>
          <span v-else>-</span>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ customer.createdTime }}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="3">{{ customer.remark || '无' }}</el-descriptions-item>
      </el-descriptions>

      <!-- 统计信息 -->
      <el-descriptions title="统计信息" :column="3" border class="info-section">
        <el-descriptions-item label="跟进次数">{{ customer.followUpCount || 0 }}</el-descriptions-item>
        <el-descriptions-item label="最后跟进时间">{{ customer.lastFollowUpTime || '-' }}</el-descriptions-item>
        <el-descriptions-item label="下次跟进时间">{{ customer.nextFollowUpTime || '-' }}</el-descriptions-item>
        <el-descriptions-item label="分配次数">{{ customer.allocationCount || 0 }}</el-descriptions-item>
        <el-descriptions-item label="最后分配时间">{{ customer.lastAllocationTime || '-' }}</el-descriptions-item>
        <el-descriptions-item label="状态变更次数">{{ customer.statusChangeCount || 0 }}</el-descriptions-item>
      </el-descriptions>

      <!-- 跟进记录 -->
      <div class="section-container">
        <div class="section-header">
          <h3>跟进记录</h3>
          <el-button type="primary" size="small" @click="handleFollowUp">新增跟进</el-button>
        </div>
        <el-table :data="followUpList" border style="width: 100%">
          <el-table-column prop="followUpTime" label="跟进时间" width="160" />
          <el-table-column prop="followUpMethod" label="跟进方式" width="100">
            <template #default="{ row }">
              <el-tag size="small">{{ getFollowUpMethodLabel(row.followUpMethod) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="customerIntention" label="客户意向" width="100">
            <template #default="{ row }">
              <el-tag size="small" :type="getIntentionType(row.customerIntention)">
                {{ getIntentionLabel(row.customerIntention) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="followUpContent" label="跟进内容" min-width="200" show-overflow-tooltip />
          <el-table-column prop="nextFollowUpTime" label="下次跟进时间" width="160" />
          <el-table-column prop="followUpUserName" label="跟进人" width="100" />
          <el-table-column label="操作" width="100" fixed="right">
            <template #default="{ row }">
              <el-button type="text" @click="handleViewFollowUp(row)">查看</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          v-model:current-page="followUpPagination.currentPage"
          v-model:page-size="followUpPagination.pageSize"
          :total="followUpPagination.total"
          :page-sizes="[10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleFollowUpSizeChange"
          @current-change="handleFollowUpCurrentChange"
          class="pagination"
        />
      </div>

      <!-- 分配记录 -->
      <div class="section-container">
        <div class="section-header">
          <h3>分配记录</h3>
        </div>
        <el-table :data="allocationList" border style="width: 100%">
          <el-table-column prop="allocationTime" label="分配时间" width="160" />
          <el-table-column prop="allocatorName" label="分配人" width="100" />
          <el-table-column prop="assigneeName" label="接收人" width="100" />
          <el-table-column prop="allocationStatus" label="分配状态" width="100">
            <template #default="{ row }">
              <el-tag size="small" :type="getAllocationStatusType(row.allocationStatus)">
                {{ getAllocationStatusLabel(row.allocationStatus) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="分配说明" min-width="200" show-overflow-tooltip />
          <el-table-column prop="processedTime" label="处理时间" width="160" />
        </el-table>
        <el-pagination
          v-model:current-page="allocationPagination.currentPage"
          v-model:page-size="allocationPagination.pageSize"
          :total="allocationPagination.total"
          :page-sizes="[10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleAllocationSizeChange"
          @current-change="handleAllocationCurrentChange"
          class="pagination"
        />
      </div>

      <!-- 状态变更记录 -->
      <div class="section-container">
        <div class="section-header">
          <h3>状态变更记录</h3>
          <div class="section-actions">
            <el-radio-group v-model="statusChangeViewMode" size="small">
              <el-radio-button label="table">表格视图</el-radio-button>
              <el-radio-button label="timeline">时间轴视图</el-radio-button>
            </el-radio-group>
            <el-button type="primary" size="small" @click="exportStatusChanges" :loading="exportLoading">
              导出记录
            </el-button>
          </div>
        </div>
        
        <!-- 待审批提醒 -->
        <el-alert
          v-if="approvalList.length > 0 && hasApprovalPermission"
          title="有待审批的状态变更申请"
          type="warning"
          :closable="false"
          style="margin-bottom: 20px">
          <div class="approval-summary">
            <span>共有 {{ approvalList.length }} 条状态变更申请等待审批</span>
            <el-button type="warning" size="small" @click="showApprovalList = !showApprovalList">
              {{ showApprovalList ? '隐藏' : '查看' }}待审批列表
            </el-button>
          </div>
        </el-alert>
        
        <!-- 待审批列表 -->
        <div v-if="showApprovalList && approvalList.length > 0" class="approval-list" style="margin-bottom: 20px">
          <el-table :data="approvalList" border style="width: 100%">
            <el-table-column prop="customerName" label="客户名称" min-width="120" />
            <el-table-column prop="oldStatus" label="原状态" width="100">
              <template #default="{ row }">
                <el-tag :type="getStatusType(row.oldStatus)">
                  {{ getStatusLabel(row.oldStatus) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="newStatus" label="新状态" width="100">
              <template #default="{ row }">
                <el-tag :type="getStatusType(row.newStatus)">
                  {{ getStatusLabel(row.newStatus) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="reason" label="变更原因" min-width="200" show-overflow-tooltip />
            <el-table-column prop="applicantName" label="申请人" width="100" />
            <el-table-column prop="applyTime" label="申请时间" width="160" />
            <el-table-column label="操作" width="100" fixed="right">
              <template #default="{ row }">
                <el-button type="primary" size="small" @click="openApprovalDialog(row)">
                  审批
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        
        <!-- 统计信息卡片 -->
        <el-row :gutter="20" class="stats-row" v-if="statusChangeStats.totalChanges > 0">
          <el-col :span="6">
            <el-card class="stat-card">
              <div class="stat-item">
                <div class="stat-label">总变更次数</div>
                <div class="stat-value">{{ statusChangeStats.totalChanges }}</div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="stat-card">
              <div class="stat-item">
                <div class="stat-label">近30天变更</div>
                <div class="stat-value">{{ statusChangeStats.recentChanges }}</div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="12">
            <el-card class="stat-card">
              <div class="stat-item">
                <div class="stat-label">状态分布</div>
                <div class="stat-distribution">
                  <span v-for="(count, status) in statusChangeStats.statusDistribution" :key="status" class="distribution-item">
                    <el-tag size="small" :type="getStatusType(status)">
                      {{ getStatusLabel(status) }}: {{ count }}
                    </el-tag>
                  </span>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
        <!-- 表格视图 -->
        <el-table :data="statusChangeList" border style="width: 100%" v-if="statusChangeViewMode === 'table'">
          <el-table-column prop="operatorTime" label="变更时间" width="160" />
          <el-table-column prop="oldStatus" label="原状态" width="100">
            <template #default="{ row }">
              <el-tag size="small">{{ getStatusLabel(row.oldStatus) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="newStatus" label="新状态" width="100">
            <template #default="{ row }">
              <el-tag size="small" :type="getStatusType(row.newStatus)">
                {{ getStatusLabel(row.newStatus) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="changeReason" label="变更原因" min-width="200" show-overflow-tooltip />
          <el-table-column prop="operatorName" label="操作人" width="100" />
          <el-table-column prop="approvalStatus" label="审批状态" width="100">
            <template #default="{ row }">
              <el-tag 
                v-if="row.approvalStatus" 
                :type="getApprovalStatusType(row.approvalStatus)"
                size="small">
                {{ getApprovalStatusLabel(row.approvalStatus) }}
              </el-tag>
              <span v-else>-</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120" fixed="right">
            <template #default="{ row }">
              <el-button 
                v-if="row.approvalStatus === 'pending' && hasApprovalPermission"
                type="primary" 
                size="small"
                @click="openApprovalDialog(row)">
                审批
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 时间轴视图 -->
        <div class="timeline-container" v-if="statusChangeViewMode === 'timeline'">
          <el-timeline>
            <el-timeline-item 
              v-for="item in statusChangeList" 
              :key="item.id"
              :timestamp="item.operatorTime"
              :color="getStatusColor(item.newStatus)"
              placement="top">
              <el-card class="timeline-card">
                <div class="timeline-header">
                   <span class="operator">{{ item.operatorName }}</span>
                   <span class="reason-type">{{ getReasonTypeLabel(item.reasonType) }}</span>
                   <el-tag 
                     v-if="item.approvalStatus" 
                     :type="getApprovalStatusType(item.approvalStatus)"
                     size="small">
                     {{ getApprovalStatusLabel(item.approvalStatus) }}
                   </el-tag>
                </div>
                <div class="timeline-content">
                   <div class="status-change">
                     <el-tag :type="getStatusType(item.oldStatus)" size="small">
                       {{ getStatusLabel(item.oldStatus) }}
                     </el-tag>
                     <el-icon class="arrow-icon"><ArrowRight /></el-icon>
                     <el-tag :type="getStatusType(item.newStatus)" size="small">
                       {{ getStatusLabel(item.newStatus) }}
                     </el-tag>
                   </div>
                   <div class="reason-text">{{ item.reason }}</div>
                 </div>
              </el-card>
            </el-timeline-item>
          </el-timeline>
        </div>
        <el-pagination
          v-model:current-page="statusChangePagination.currentPage"
          v-model:page-size="statusChangePagination.pageSize"
          :total="statusChangePagination.total"
          :page-sizes="[10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleStatusChangeSizeChange"
          @current-change="handleStatusChangeCurrentChange"
          class="pagination"
        />
      </div>
    </el-card>

    <!-- 跟进详情对话框 -->
    <el-dialog
      v-model="followUpDetailDialog.visible"
      title="跟进详情"
      width="600px"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="跟进时间">{{ followUpDetailDialog.data.followUpTime }}</el-descriptions-item>
        <el-descriptions-item label="跟进方式">
          <el-tag size="small">{{ getFollowUpMethodLabel(followUpDetailDialog.data.followUpMethod) }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="客户意向">
          <el-tag size="small" :type="getIntentionType(followUpDetailDialog.data.customerIntention)">
            {{ getIntentionLabel(followUpDetailDialog.data.customerIntention) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="下次跟进时间">{{ followUpDetailDialog.data.nextFollowUpTime || '-' }}</el-descriptions-item>
        <el-descriptions-item label="跟进人">{{ followUpDetailDialog.data.followUpUserName }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ followUpDetailDialog.data.createdTime }}</el-descriptions-item>
        <el-descriptions-item label="跟进内容" :span="2">{{ followUpDetailDialog.data.followUpContent }}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ followUpDetailDialog.data.remark || '无' }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button @click="followUpDetailDialog.visible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 客户转移对话框 -->
    <el-dialog
      v-model="transferDialog.visible"
      title="客户转移"
      width="500px"
    >
      <el-form :model="transferDialog.form" label-width="100px">
        <el-form-item label="目标用户">
          <el-select v-model="transferDialog.form.targetUserId" placeholder="请选择目标用户">
            <el-option
              v-for="user in userOptions"
              :key="user.id"
              :label="user.userName"
              :value="user.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="转移说明">
          <el-input
            v-model="transferDialog.form.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入转移说明"
          />
        </el-form-item>
        <el-form-item label="需要审批">
          <el-switch
            v-model="transferDialog.form.requireApproval"
            active-text="是"
            inactive-text="否"
          />
          <div class="approval-tips" v-if="transferDialog.form.requireApproval">
            <el-alert
              title="重要客户转移需要审批，审批流程将在提交后启动"
              type="warning"
              :closable="false"
              show-icon
            />
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="transferDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmitTransfer" :loading="transferDialog.loading">
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 状态变更对话框 -->
    <el-dialog
      v-model="statusChangeDialog.visible"
      title="状态变更"
      width="500px"
      @closed="resetStatusChangeForm"
    >
      <el-form 
        ref="statusChangeFormRef"
        :model="statusChangeDialog.form" 
        :rules="statusChangeDialog.rules"
        label-width="100px"
      >
        <el-form-item label="新状态">
          <el-tag :type="getStatusType(statusChangeDialog.form.newStatus)">
            {{ getStatusLabel(statusChangeDialog.form.newStatus) }}
          </el-tag>
        </el-form-item>
        <el-form-item label="变更原因类型" prop="reasonType">
          <el-select v-model="statusChangeDialog.form.reasonType" placeholder="请选择变更原因类型">
            <el-option
              v-for="option in statusChangeReasonOptions"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="详细原因" prop="reason">
          <el-input
            v-model="statusChangeDialog.form.reason"
            type="textarea"
            :rows="3"
            placeholder="请输入详细的状态变更原因"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="需要审批" v-if="statusChangeDialog.form.requireApproval">
          <el-alert
            title="当前状态变更需要上级审批，提交后将进入审批流程"
            type="warning"
            :closable="false"
            show-icon
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="statusChangeDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmitStatusChange" :loading="statusChangeDialog.loading">
          确定
        </el-button>
      </template>
    </el-dialog>
    
    <!-- 审批对话框 -->
    <el-dialog
      v-model="approvalDialog.visible"
      title="状态变更审批"
      width="500px"
      :close-on-click-modal="false">
      <el-form
        ref="approvalFormRef"
        :model="approvalDialog.form"
        :rules="approvalDialog.rules"
        label-width="80px">
        <el-form-item label="客户名称">
          <el-input :value="approvalDialog.currentApproval?.customerName" disabled />
        </el-form-item>
        <el-form-item label="原状态">
          <el-tag :type="getStatusType(approvalDialog.currentApproval?.oldStatus)">
            {{ getStatusLabel(approvalDialog.currentApproval?.oldStatus) }}
          </el-tag>
        </el-form-item>
        <el-form-item label="新状态">
          <el-tag :type="getStatusType(approvalDialog.currentApproval?.newStatus)">
            {{ getStatusLabel(approvalDialog.currentApproval?.newStatus) }}
          </el-tag>
        </el-form-item>
        <el-form-item label="变更原因">
          <el-input
            type="textarea"
            :value="approvalDialog.currentApproval?.reason"
            :rows="3"
            disabled />
        </el-form-item>
        <el-form-item label="原因类型">
          <el-input :value="getReasonTypeLabel(approvalDialog.currentApproval?.reasonType)" disabled />
        </el-form-item>
        <el-form-item label="申请人">
          <el-input :value="approvalDialog.currentApproval?.applicantName" disabled />
        </el-form-item>
        <el-form-item label="申请时间">
          <el-input :value="approvalDialog.currentApproval?.applyTime" disabled />
        </el-form-item>
        <el-form-item label="审批意见" prop="comment">
          <el-input
            v-model="approvalDialog.form.comment"
            type="textarea"
            :rows="3"
            placeholder="请输入审批意见"
            maxlength="200"
            show-word-limit />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="approvalDialog.visible = false">取消</el-button>
          <el-button type="danger" @click="submitRejection(approvalFormRef)" :loading="approvalDialog.loading">
            拒绝
          </el-button>
          <el-button type="primary" @click="submitApproval(approvalFormRef)" :loading="approvalDialog.loading">
            批准
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowRight } from '@element-plus/icons-vue'
import { 
  getCustomerDetail, 
  getCustomerFollowUps, 
  getCustomerAllocations, 
  getCustomerStatusHistory, 
  transferCustomer, 
  markCustomerInvalid, 
  batchUpdateCustomerStatus,
  getUserList,
  getStatusChangeApprovals,
  approveStatusChange,
  rejectStatusChange
} from '@/api/crm'

const route = useRoute()
const router = useRouter()
const customerId = route.params.id as string

// 客户基本信息
const customer = ref({
  customerName: '',
  phone: '',
  customerStatus: '',
  customerSource: '',
  channelName: '',
  ownerUserName: '',
  allocationStatus: '',
  loanAmount: 0,
  followUpCount: 0,
  lastFollowUpTime: '',
  nextFollowUpTime: '',
  allocationCount: 0,
  lastAllocationTime: '',
  statusChangeCount: 0,
  createdTime: '',
  remark: ''
})

// 跟进记录
const followUpList = ref([])
const followUpPagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 分配记录
const allocationList = ref([])
const allocationPagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 状态变更相关
const statusChangeList = ref([])
const statusChangePagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})
const statusChangeViewMode = ref('table') // 视图模式：table/timeline
const exportLoading = ref(false)
const statusChangeStats = reactive({
  totalChanges: 0,
  recentChanges: 0,
  statusDistribution: {} as Record<string, number>,
  changeTrend: [] as Array<{month: string, count: number}>
})

// 审批相关
const approvalList = ref([])
const approvalPagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})
const approvalDialog = reactive({
  visible: false,
  loading: false,
  currentApproval: null as any,
  form: {
    comment: ''
  },
  rules: {
    comment: [
      { required: true, message: '请输入审批意见', trigger: 'blur' },
      { min: 2, max: 200, message: '审批意见长度在 2 到 200 个字符', trigger: 'blur' }
    ]
  },
  formRef: null as any
})

// 审批权限（实际项目中应该从用户信息获取）
const hasApprovalPermission = ref(true) // 临时设置为true，实际应该根据用户角色判断
const showApprovalList = ref(false) // 是否显示待审批列表

// 状态变更统计信息
const statusChangeStats = reactive({
  totalChanges: 0,
  recentChanges: 0,
  statusDistribution: {} as Record<string, number>,
  changeTrend: [] as any[]
})

// 用户选项
const userOptions = ref([])

// 跟进详情对话框
const followUpDetailDialog = reactive({
  visible: false,
  data: {}
})

// 客户转移对话框
const transferDialog = reactive({
  visible: false,
  loading: false,
  form: {
    targetUserId: null,
    remark: '',
    requireApproval: false
  }
})

// 状态变更对话框
const statusChangeDialog = reactive({
  visible: false,
  loading: false,
  formRef: null as any,
  form: {
    newStatus: '',
    reason: '',
    reasonType: '',
    requireApproval: false
  },
  rules: {
    reason: [
      { required: true, message: '请输入状态变更原因', trigger: 'blur' },
      { min: 5, max: 500, message: '原因长度应在5-500个字符之间', trigger: 'blur' }
    ],
    reasonType: [
      { required: true, message: '请选择变更原因类型', trigger: 'change' }
    ]
  }
})

// 审批表单引用
const approvalFormRef = ref()

// 获取状态标签
const getStatusLabel = (status: string) => {
  const labels: Record<string, string> = {
    potential: '潜在客户',
    intention: '意向客户',
    deal: '成交客户',
    invalid: '失效客户'
  }
  return labels[status] || status
}

const getStatusType = (status: string) => {
  const types: Record<string, string> = {
    potential: 'info',
    intention: 'warning',
    deal: 'success',
    invalid: 'danger'
  }
  return types[status] || 'info'
}

// 获取来源标签
const getSourceLabel = (source: string) => {
  const labels: Record<string, string> = {
    online: '线上推广',
    offline: '线下推广',
    referral: '转介绍',
    organic: '自然流量'
  }
  return labels[source] || source
}

// 获取跟进方式标签
const getFollowUpMethodLabel = (method: string) => {
  const labels: Record<string, string> = {
    phone: '电话',
    wechat: '微信',
    email: '邮件',
    visit: '上门',
    sms: '短信'
  }
  return labels[method] || method
}

// 获取意向标签
const getIntentionLabel = (intention: string) => {
  const labels: Record<string, string> = {
    A: 'A级（高意向）',
    B: 'B级（中意向）',
    C: 'C级（低意向）',
    D: 'D级（无意向）'
  }
  return labels[intention] || intention
}

const getIntentionType = (intention: string) => {
  const types: Record<string, string> = {
    A: 'success',
    B: 'warning',
    C: 'info',
    D: 'danger'
  }
  return types[intention] || 'info'
}

// 获取分配状态标签
const getAllocationStatusLabel = (status: string) => {
  const labels: Record<string, string> = {
    pending: '待处理',
    accepted: '已接受',
    rejected: '已拒绝'
  }
  return labels[status] || status
}

const getAllocationStatusType = (status: string) => {
  const types: Record<string, string> = {
    pending: 'warning',
    accepted: 'success',
    rejected: 'danger'
  }
  return types[status] || 'info'
}

// 格式化货币
const formatCurrency = (amount: number) => {
  return `¥${amount.toLocaleString()}`
}

// 返回
const goBack = () => {
  router.push('/crm/customer')
}

// 编辑客户
const handleEdit = () => {
  router.push(`/crm/customer/edit/${customerId}`)
}

// 新增跟进
const handleFollowUp = () => {
  router.push(`/crm/follow-up?customerId=${customerId}`)
}

// 查看跟进详情
const handleViewFollowUp = (row: any) => {
  followUpDetailDialog.data = row
  followUpDetailDialog.visible = true
}

// 客户转移
const handleTransfer = () => {
  transferDialog.visible = true
  transferDialog.form.targetUserId = null
  transferDialog.form.remark = ''
  transferDialog.form.requireApproval = false // 默认不需要审批
}

// 状态变更原因类型选项
const statusChangeReasonOptions = [
  { label: '客户主动要求', value: 'customer_request' },
  { label: '跟进结果评估', value: 'follow_up_assessment' },
  { label: '客户意向变化', value: 'intention_change' },
  { label: '成交状态更新', value: 'deal_update' },
  { label: '客户流失', value: 'customer_churn' },
  { label: '信息核实结果', value: 'information_verification' },
  { label: '其他原因', value: 'other' }
]

// 需要审批的状态变更类型
const approvalRequiredStatusChanges = ['deal', 'invalid']

// 重置状态变更表单
const resetStatusChangeForm = () => {
  statusChangeDialog.form.newStatus = ''
  statusChangeDialog.form.reason = ''
  statusChangeDialog.form.reasonType = ''
  statusChangeDialog.form.requireApproval = false
  if (statusChangeDialog.formRef) {
    statusChangeDialog.formRef.resetFields()
  }
}

// 计算状态变更统计信息
const calculateStatusChangeStats = () => {
  if (!statusChangeList.value || statusChangeList.value.length === 0) {
    statusChangeStats.totalChanges = 0
    statusChangeStats.recentChanges = 0
    statusChangeStats.statusDistribution = {}
    statusChangeStats.changeTrend = []
    return
  }

  // 总变更次数
  statusChangeStats.totalChanges = statusChangeList.value.length

  // 最近30天的变更次数
  const thirtyDaysAgo = new Date()
  thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30)
  statusChangeStats.recentChanges = statusChangeList.value.filter((item: any) => {
    return new Date(item.operatorTime) >= thirtyDaysAgo
  }).length

  // 状态分布统计
  const distribution: Record<string, number> = {}
  statusChangeList.value.forEach((item: any) => {
    const newStatus = item.newStatus
    distribution[newStatus] = (distribution[newStatus] || 0) + 1
  })
  statusChangeStats.statusDistribution = distribution

  // 趋势分析（按月份分组）
  const trendMap: Record<string, number> = {}
  statusChangeList.value.forEach((item: any) => {
    const month = item.operatorTime.substring(0, 7) // YYYY-MM格式
    trendMap[month] = (trendMap[month] || 0) + 1
  })
  
  // 转换为数组并排序
  statusChangeStats.changeTrend = Object.entries(trendMap)
    .map(([month, count]) => ({ month, count }))
    .sort((a, b) => a.month.localeCompare(b.month))
    .slice(-6) // 只显示最近6个月
}

// 获取状态分布的环形图数据
const getStatusDistributionData = () => {
  const data = Object.entries(statusChangeStats.statusDistribution).map(([status, count]) => ({
    name: getStatusLabel(status),
    value: count
  }))
  return data
}

// 获取原因类型标签
const getReasonTypeLabel = (reasonType: string) => {
  const reasonTypeMap: Record<string, string> = {
    'customer_request': '客户要求',
    'business_need': '业务需要',
    'quality_issue': '质量问题',
    'service_issue': '服务问题',
    'price_issue': '价格问题',
    'competitor': '竞争对手',
    'internal_error': '内部错误',
    'other': '其他原因'
  }
  return reasonTypeMap[reasonType] || reasonType
}

// 获取状态颜色
const getStatusColor = (status: string) => {
  const colorMap: Record<string, string> = {
    'potential': '#409EFF',
    'intention': '#67C23A',
    'negotiation': '#E6A23C',
    'deal': '#67C23A',
    'invalid': '#F56C6C'
  }
  return colorMap[status] || '#909399'
}

// 获取审批状态标签
const getApprovalStatusLabel = (status: string) => {
  const statusMap: Record<string, string> = {
    'pending': '待审批',
    'approved': '已批准',
    'rejected': '已拒绝',
    'cancelled': '已取消'
  }
  return statusMap[status] || status
}

// 获取审批状态类型
const getApprovalStatusType = (status: string) => {
  const typeMap: Record<string, string> = {
    'pending': 'warning',
    'approved': 'success',
    'rejected': 'danger',
    'cancelled': 'info'
  }
  return typeMap[status] || 'info'
}

// 导出状态变更记录
const exportStatusChanges = async () => {
  try {
    exportLoading.value = true
    
    // 获取所有状态变更记录（不分页）
    const allChanges = await getCustomerStatusHistory(customerId, {
      pageNum: 1,
      pageSize: 1000 // 假设最多1000条记录
    })
    
    if (!allChanges.rows || allChanges.rows.length === 0) {
      ElMessage.warning('暂无状态变更记录可导出')
      return
    }
    
    // 准备导出数据
    const exportData = allChanges.rows.map((item: any) => ({
      '变更时间': item.operatorTime,
      '操作人': item.operatorName,
      '原状态': getStatusLabel(item.oldStatus),
      '新状态': getStatusLabel(item.newStatus),
      '变更原因': item.reason,
      '原因类型': getReasonTypeLabel(item.reasonType)
    }))
    
    // 创建CSV内容
    const headers = Object.keys(exportData[0])
    const csvContent = [
      headers.join(','),
      ...exportData.map((row: any) => 
        headers.map(header => `"${row[header] || ''}"`).join(',')
      )
    ].join('\n')
    
    // 创建下载链接
    const blob = new Blob(['\uFEFF' + csvContent], { type: 'text/csv;charset=utf-8;' })
    const link = document.createElement('a')
    const url = URL.createObjectURL(blob)
    link.setAttribute('href', url)
    link.setAttribute('download', `客户状态变更记录_${customerDetail.value.name}_${new Date().toISOString().split('T')[0]}.csv`)
    link.style.visibility = 'hidden'
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    
    ElMessage.success('状态变更记录导出成功')
  } catch (error: any) {
    const errorMessage = error?.response?.data?.message || error?.message || '导出失败'
    ElMessage.error(errorMessage)
    console.error('导出状态变更记录失败:', error)
  } finally {
    exportLoading.value = false
  }
}

// 获取待审批的状态变更
const fetchStatusChangeApprovals = async () => {
  try {
    const params = {
      pageNum: approvalPagination.currentPage,
      pageSize: approvalPagination.pageSize,
      customerId: customerId
    }
    const res = await getStatusChangeApprovals(params)
    approvalList.value = res.rows
    approvalPagination.total = res.total
  } catch (error: any) {
    const errorMessage = error?.response?.data?.message || error?.message || '获取审批列表失败'
    ElMessage.error(errorMessage)
    console.error('获取审批列表失败:', error)
  }
}

// 打开审批对话框
const openApprovalDialog = (approval: any) => {
  approvalDialog.currentApproval = approval
  approvalDialog.form.comment = ''
  approvalDialog.visible = true
}

// 提交审批（批准）
const submitApproval = async (formRef: any) => {
  if (!formRef) return
  
  await formRef.validate(async (valid: boolean) => {
    if (valid) {
      try {
        approvalDialog.loading = true
        await approveStatusChange(approvalDialog.currentApproval.id, {
          comment: approvalDialog.form.comment
        })
        ElMessage.success('审批通过')
        approvalDialog.visible = false
        // 刷新状态变更记录和审批列表
        fetchStatusChanges()
        fetchStatusChangeApprovals()
      } catch (error: any) {
        const errorMessage = error?.response?.data?.message || error?.message || '审批失败'
        ElMessage.error(errorMessage)
        console.error('审批失败:', error)
      } finally {
        approvalDialog.loading = false
      }
    }
  })
}

// 提交拒绝
const submitRejection = async (formRef: any) => {
  if (!formRef) return
  
  await formRef.validate(async (valid: boolean) => {
    if (valid) {
      try {
        approvalDialog.loading = true
        await rejectStatusChange(approvalDialog.currentApproval.id, {
          comment: approvalDialog.form.comment
        })
        ElMessage.success('已拒绝状态变更申请')
        approvalDialog.visible = false
        // 刷新状态变更记录和审批列表
        fetchStatusChanges()
        fetchStatusChangeApprovals()
      } catch (error: any) {
        const errorMessage = error?.response?.data?.message || error?.message || '拒绝失败'
        ElMessage.error(errorMessage)
        console.error('拒绝失败:', error)
      } finally {
        approvalDialog.loading = false
      }
    }
  })
}

// 状态变更操作
const handleStatusAction = (command: string) => {
  statusChangeDialog.form.newStatus = command
  statusChangeDialog.form.reason = ''
  statusChangeDialog.form.reasonType = ''
  // 根据目标状态判断是否需要审批
  statusChangeDialog.form.requireApproval = approvalRequiredStatusChanges.includes(command)
  statusChangeDialog.visible = true
}

// 提交客户转移
const handleSubmitTransfer = async () => {
  if (!transferDialog.form.targetUserId) {
    ElMessage.warning('请选择目标用户')
    return
  }
  
  transferDialog.loading = true
  try {
    const transferData = {
      customerId: parseInt(customerId),
      fromUserId: customer.value.ownerUserId,
      toUserId: transferDialog.form.targetUserId,
      remark: transferDialog.form.remark,
      requireApproval: transferDialog.form.requireApproval
    }
    
    await transferCustomer(transferData)
    
    if (transferDialog.form.requireApproval) {
      ElMessage.success('客户转移申请已提交，等待审批')
    } else {
      ElMessage.success('客户转移成功')
    }
    
    transferDialog.visible = false
    fetchCustomerDetail()
    fetchAllocations()
  } catch (error: any) {
    const errorMessage = error?.response?.data?.message || error?.message || '客户转移失败'
    ElMessage.error(errorMessage)
    console.error('客户转移失败:', error)
  } finally {
    transferDialog.loading = false
  }
}

// 提交状态变更
const handleSubmitStatusChange = async () => {
  // 表单验证
  const formRef = statusChangeDialog.formRef
  if (formRef) {
    try {
      await formRef.validate()
    } catch (error) {
      return // 验证失败，不提交
    }
  }
  
  statusChangeDialog.loading = true
  try {
    const requestData = {
      customerIds: [parseInt(customerId)],
      targetStatus: statusChangeDialog.form.newStatus,
      reason: statusChangeDialog.form.reason,
      reasonType: statusChangeDialog.form.reasonType,
      requireApproval: statusChangeDialog.form.requireApproval
    }
    
    await batchUpdateCustomerStatus(requestData)
    
    if (statusChangeDialog.form.requireApproval) {
      ElMessage.success('状态变更申请已提交，等待审批')
    } else {
      ElMessage.success('状态变更成功')
    }
    
    statusChangeDialog.visible = false
    fetchCustomerDetail()
    fetchStatusChanges()
  } catch (error: any) {
    const errorMessage = error?.response?.data?.message || error?.message || '状态变更失败'
    ElMessage.error(errorMessage)
    console.error('状态变更失败:', error)
  } finally {
    statusChangeDialog.loading = false
  }
}

// 获取客户详情
const fetchCustomerDetail = async () => {
  try {
    const res = await getCustomerDetail(customerId)
    customer.value = res.data
  } catch (error: any) {
    const errorMessage = error?.response?.data?.message || error?.message || '获取客户详情失败'
    ElMessage.error(errorMessage)
    console.error('获取客户详情失败:', error)
  }
}

// 获取跟进记录
const fetchFollowUps = async () => {
  try {
    const params = {
      customerId,
      pageNum: followUpPagination.currentPage,
      pageSize: followUpPagination.pageSize
    }
    const res = await getCustomerFollowUps(params)
    followUpList.value = res.rows
    followUpPagination.total = res.total
  } catch (error: any) {
    const errorMessage = error?.response?.data?.message || error?.message || '获取跟进记录失败'
    ElMessage.error(errorMessage)
    console.error('获取跟进记录失败:', error)
  }
}

// 获取分配记录
const fetchAllocations = async () => {
  try {
    const params = {
      customerId,
      pageNum: allocationPagination.currentPage,
      pageSize: allocationPagination.pageSize
    }
    const res = await getCustomerAllocations(params)
    allocationList.value = res.rows
    allocationPagination.total = res.total
  } catch (error: any) {
    const errorMessage = error?.response?.data?.message || error?.message || '获取分配记录失败'
    ElMessage.error(errorMessage)
    console.error('获取分配记录失败:', error)
  }
}

// 获取状态变更记录
const fetchStatusChanges = async () => {
  try {
    const params = {
      pageNum: statusChangePagination.currentPage,
      pageSize: statusChangePagination.pageSize
    }
    const res = await getCustomerStatusHistory(customerId, params)
    statusChangeList.value = res.rows
    statusChangePagination.total = res.total
    
    // 计算统计信息
    calculateStatusChangeStats()
  } catch (error: any) {
    const errorMessage = error?.response?.data?.message || error?.message || '获取状态变更记录失败'
    ElMessage.error(errorMessage)
    console.error('获取状态变更记录失败:', error)
  }
}

// 分页处理
const handleFollowUpSizeChange = (val: number) => {
  followUpPagination.pageSize = val
  fetchFollowUps()
}

const handleFollowUpCurrentChange = (val: number) => {
  followUpPagination.currentPage = val
  fetchFollowUps()
}

const handleAllocationSizeChange = (val: number) => {
  allocationPagination.pageSize = val
  fetchAllocations()
}

const handleAllocationCurrentChange = (val: number) => {
  allocationPagination.currentPage = val
  fetchAllocations()
}

const handleStatusChangeSizeChange = (val: number) => {
  statusChangePagination.pageSize = val
  fetchStatusChanges()
}

const handleStatusChangeCurrentChange = (val: number) => {
  statusChangePagination.currentPage = val
  fetchStatusChanges()
}

// 获取用户列表
const fetchUserOptions = async () => {
  try {
    const res = await getUserList()
    userOptions.value = res
  } catch (error: any) {
    const errorMessage = error?.response?.data?.message || error?.message || '获取用户列表失败'
    ElMessage.error(errorMessage)
    console.error('获取用户列表失败:', error)
  }
}

// 初始化
onMounted(async () => {
  await fetchCustomerDetail()
  await fetchFollowUps()
  await fetchAllocations()
  await fetchStatusChanges()
  await fetchUserOptions()
  // 加载待审批的状态变更（如果有权限）
  await fetchStatusChangeApprovals()
})
</script>

<style scoped lang="scss">
.customer-detail {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .info-section {
    margin-bottom: 30px;
  }

  .section-container {
    margin-bottom: 30px;

    .section-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 15px;

      h3 {
        margin: 0;
        font-size: 16px;
        font-weight: 600;
      }

      .section-actions {
        display: flex;
        gap: 10px;
        align-items: center;
      }
    }
  }

  // 统计信息样式
  .stats-row {
    margin-bottom: 20px;

    .stat-card {
      .stat-item {
        text-align: center;
        padding: 10px;

        .stat-label {
          font-size: 14px;
          color: #909399;
          margin-bottom: 8px;
        }

        .stat-value {
          font-size: 24px;
          font-weight: bold;
          color: #303133;
        }

        .stat-distribution {
          display: flex;
          flex-wrap: wrap;
          gap: 8px;
          justify-content: center;

          .distribution-item {
            display: inline-block;
          }
        }
      }
    }
  }

  // 时间轴样式
  .timeline-container {
    padding: 20px;
    background-color: #fafafa;
    border-radius: 8px;

    .timeline-card {
      margin-bottom: 10px;

      .timeline-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 10px;

        .operator {
          font-weight: 500;
          color: #303133;
        }

        .reason-type {
          font-size: 12px;
          color: #909399;
        }
      }

      .timeline-content {
        .status-change {
          display: flex;
          align-items: center;
          gap: 8px;
          margin-bottom: 8px;

          .arrow-icon {
            color: #909399;
            font-size: 14px;
          }
        }

        .reason-text {
          font-size: 14px;
          color: #606266;
          line-height: 1.5;
        }
      }
    }
  }

  // 审批相关样式
  .approval-summary {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .approval-list {
    background-color: #fafafa;
    border-radius: 8px;
    padding: 15px;
  }

  .pagination {
    margin-top: 15px;
    display: flex;
    justify-content: flex-end;
  }

  .approval-tips {
    margin-top: 8px;
    width: 100%;
  }

  // 响应式设计
  @media screen and (max-width: 768px) {
    .card-header {
      flex-direction: column;
      align-items: flex-start;
      gap: 10px;
    }

    .section-header {
      flex-direction: column;
      align-items: flex-start;
      gap: 10px;
    }

    .pagination {
      justify-content: center;
    }
  }
}
</style>